package com.zhlq.util;

import java.io.IOException;
import java.io.StringWriter;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * @ClassName JsonUtil
 * @Description Json工具
 * @author ZHLQ
 * @date 2015年6月7日 上午1:55:41
 */
public class JsonUtil {

	/**
	 * toJson
	 *
	 * @Title toJson
	 * @Description 对象转换为Json
	 * @param object对象
	 * @throws IOException 设定文件
	 * @return String 返回类型
	 */
	public static String toJson(Object object) throws IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		StringWriter sw = new StringWriter();
		JsonGenerator jsonGenerator = null;
		try {
			jsonGenerator = new JsonFactory().createJsonGenerator(sw);
			objectMapper.writeValue(jsonGenerator, object);
		} finally {
			if (null != jsonGenerator) {
	            jsonGenerator.flush();
	        }
	        if (!jsonGenerator.isClosed()) {
	            jsonGenerator.close();
	        }
	        jsonGenerator = null;
	        objectMapper = null;
		}
		return sw.toString();
	}

	/**
	 * toObject
	 *
	 * @Title toObject
	 * @Description Json转换为对象
	 * @param json
	 * @param clazz
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException 设定文件
	 * @return Object 返回类型
	 */
	public static Object toObject(String json, Class<?> clazz) throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		return objectMapper.readValue(json, clazz);
	}

	/**
	 * 创建一个新的实例 JsonUtil。
	 * 
	 * @Title: JsonUtil
	 * @Description: 私有无参构造方法
	 */
	private JsonUtil() {
		super();
	}
}
